const express = require('express')
const fs = require('fs')

const router = express.Router()
const rootPath = './uploads/images/'
router.post('/', async (req, res) => {
  try {
    if (!req.files) {
      res.status(500).send({
        status: false,
        message: 'No file uploaded',
      })
    } else {
      let avatar = req.files.upload
      const ext = avatar.name.substring(avatar.name.lastIndexOf('.'))
      const filename = new Date().getTime() + ext
      avatar.mv(rootPath + filename)
      res.send(filename)
    }
  } catch (err) {
    res.status(500).send(err)
  }
})

router.post('/style', async (req, res) => {
  try {
    if (!req.files) {
      res.status(500).send({
        status: false,
        message: 'No file uploaded',
      })
    } else {
      const stylePath = './uploads/high/'
      let avatar = req.files.upload
      avatar.mv(stylePath + avatar.name)
      res.send(avatar.name)
    }
  } catch (err) {
    res.status(500).send(err)
  }
})

router.delete('/', async function (req, res, next) {
  const filename = req.text.toString()
  const path = rootPath + filename
  console.log(path)
  if (fs.existsSync(path)) {
    fs.unlinkSync(path)
  }
  res.send('')
})

module.exports = router
